package com.li.controller;

import com.li.DTO.CommonResult;
import com.li.entity.User;
import com.li.service.UserService;
import com.li.utils.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@Log4j2
@RestController
@Api(tags = "用户登录菜单")
public class UserController {

    @Resource
    UserService userService;

    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public CommonResult login(@RequestParam("username") String username, @RequestParam("password") String password) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);
        User user = userService.getUser(username);
//        subject.login(token);
        if (user.getPassword().equals(password)) {
            return new CommonResult(20000, "成功", JWTUtil.sign(username, password));
        }

//        String jwtToken = JwtUtil.getJwtToken(username, "11111");
//        JwtToken jwtToken1 = new JwtToken(jwtToken);
//        log.info(token.getHost());
        // 执行认证登陆
//        try {
//            subject.login(token);
//        } catch (UnknownAccountException uae) {
//            return "未知账户";
//        } catch (IncorrectCredentialsException ice) {
//            return "密码不正确";
//        } catch (LockedAccountException lae) {
//            return "账户已锁定";
//        } catch (ExcessiveAttemptsException eae) {
//            return "用户名或密码错误次数过多";
//        } catch (AuthenticationException ae) {
//            return "用户名或密码不正确！";
//        }
//        if (subject.isAuthenticated()) {
//            return "登录成功";
////            return jwtToken1;
//        } else {
//            token.clear();
//            return "登录失败";
//        }
        return null;
    }

    @PostMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        String username = (String) SecurityUtils.getSubject().getPrincipal();
//        log.info(username);
        return "退出成功";
    }
}
